package org.example.app.controller;


import lombok.extern.slf4j.Slf4j;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 图片服务器控制器
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Value("${system.baseMediaUrl}")
    private String BASE_MEDIA_URL; //存储路径

    /**
     * 获取所有文件列表
     * @return
     * @throws IOException
     */
    @GetMapping("/list")
    public R listAllFiles(@RequestParam("mediaPath") String mediaPath) throws IOException {
        String relativePath = mediaPath.substring(0, mediaPath.lastIndexOf('.'));
        String directory = BASE_MEDIA_URL + relativePath + "/";
        // 使用Java NIO的Files类遍历目录
        List<String> fileNames = Files.walk(Paths.get(directory))
                .filter(Files::isRegularFile)
                .map(file -> relativePath + "/" + file.getFileName().toString())
                .collect(Collectors.toList());
        return R.ok(fileNames);
    }
}